package yang.itcode.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yang.itcode.exception.BusinessException;
import yang.itcode.mapper.UserMapper;
import yang.itcode.model.pojo.User;
import yang.itcode.service.UserService;
import yang.itcode.utils.JwtUtil;
import yang.itcode.utils.ThreadUtil;

import java.util.HashMap;
import java.util.Map;

import static yang.itcode.constant.ErrorConstant.*;
import static yang.itcode.constant.JwtConstant.JWT_ID;
import static yang.itcode.constant.JwtConstant.JWT_SECRET;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public String login(String name, String password) {
        if (StrUtil.isBlank(name)) {
            throw new BusinessException(LOGIN_EXCEPTION_CODE, LOGIN_USERNAME_NULL_MESSAGE);
        }
        if (StrUtil.isBlank(password)) {
            throw new BusinessException(LOGIN_EXCEPTION_CODE, LOGIN_PASSWORD_NULL_MESSAGE);
        }
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        user = userMapper.selectByUsernameAndPassword(user);
        if (user == null) {
            throw new BusinessException(LOGIN_EXCEPTION_CODE, LOGIN_EXCEPTION_MESSAGE);
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWT_ID, user.getId());
        return JwtUtil.createJWT(JWT_SECRET, claims);
    }

    @Override
    public JSONObject getUserInfo() {
        Integer userId = ThreadUtil.getCurrentId();
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(USER_NOT_EXIST_EXCEPTION_CODE, USER_NOT_EXIST_EXCEPTION_MESSAGE);
        }
        JSONObject userJson = new JSONObject();
        userJson.put("name", user.getName());
        return userJson;
    }
}
